package com.allwees.bs.c.module.order.service.impl;

import com.allwees.bs.c.module.order.chain.create.handler.CalculateDiscountHandler;
import com.allwees.bs.c.module.order.chain.create.handler.CalculateOrderAmtHandler;
import com.allwees.bs.c.module.order.chain.create.handler.OrderCreatePrepareHandler;
import com.allwees.bs.c.module.order.chain.create.handler.OrderSaveHandler;
import com.allwees.bs.c.module.order.chain.create.handler.OrderSavedHandler;
import com.allwees.bs.c.module.order.chain.create.handler.OrderSkuSnapSaveHandler;
import com.allwees.bs.c.module.order.chain.create.request.OrderCreateRequest;
import com.allwees.bs.c.module.order.chain.create.request.OrderItemCreateRequest;
import com.allwees.bs.c.module.order.context.event.OrderCreatedEvent;
import com.allwees.bs.c.module.order.dto.OrderDTO;
import com.allwees.bs.c.module.order.entity.CartEntity;
import com.allwees.bs.c.module.order.mapper.OrderMapper;
import com.allwees.bs.c.module.order.repository.CartRepository;
import com.allwees.bs.c.module.order.req.CartItemReq;
import com.allwees.bs.c.module.order.req.OrderCreateReq;
import com.allwees.bs.c.module.order.service.IOrderCreateService;
import com.allwees.bs.core.modelbase.constant.ResultEnum;
import com.allwees.bs.core.modelbase.exception.BusinessException;
import com.allwees.core.cache.RedisUtil;
import com.allwees.core.common.util.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

@Slf4j
@Service
public class OrderCreateServiceImpl implements IOrderCreateService, CommandLineRunner {

    @Autowired
    private CartRepository cartRepository;
	@Autowired
	private OrderCreatePrepareHandler orderCreatePrepareHandler;
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private ApplicationContext context;

//	@Autowired
//    private OrderLogActionUtil orderLogActionUtil;



    @Override
    public void run(String... args) throws Exception {
        orderCreatePrepareHandler
                .setNextHandler(BeanUtil.getBean(CalculateOrderAmtHandler.class))
                .setNextHandler(BeanUtil.getBean(CalculateDiscountHandler.class))
                .setNextHandler(BeanUtil.getBean(OrderSaveHandler.class))
                .setNextHandler(BeanUtil.getBean(OrderSkuSnapSaveHandler.class))
				.setNextHandler(BeanUtil.getBean(OrderSavedHandler.class));
    }

    /**
     * 计算金额
     *
     * @return
     */
//    @Override
//    @Transactional
//    public CartDTO calculateOrder(CartCheckoutReq req) {
//
//        cartService.updateCouponUuid(req.getCartUuid(), req.getUserCouponUuid());
//
//        CartDTO cart = cartService.getCart(req.getCartUuid(), true);
//
//        if (req.nonCalculateOther()) {
//            return cart;
//        }
//
//        cart = _calculateUserCoupon(cart, req.getUserCouponUuid());
//        cart = cartService.shippingStrategy(cart);
//
//        cart.setAmtSaleTax(saleTaxStrategy.strategy(cart.getAmtProduct()));
//        cart.setShowSaleTax(!MoneyUtil.isNullOrZero(cart.getAmtSaleTax()));

//        BigDecimal shippingInsuranceMoney = shippingInsuranceStrategy.strategy();
//        cart.setShowShippingInsurance(!MoneyUtil.isNullOrZero(shippingInsuranceMoney));
//
//        if (req.isBuyShippingInsurance()) {
//            cart.setAmtShippingInsurance(shippingInsuranceMoney);
//        }
//        cart.setAmt(MoneyUtil.add(cart.getAmtProduct(), cart.getAmtShipping(), cart.getAmtSaleTax(), cart.getAmtShippingInsurance()));
//        return cart;
//    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDTO createOrder(String userUuid, OrderCreateReq createReq, String orderChannelUuid) {
        if(!RedisUtil.setNx(userUuid,"",3000)) {
            throw BusinessException.getInstance(ResultEnum.EXCEED_ACCESS_LIMIT);
        }
        CartEntity cart = cartRepository.getByUser(userUuid);
        OrderCreateRequest req = new OrderCreateRequest()
                .setUserUuid(userUuid)
				.setInviterUserUuid(createReq.getInviterUserUuid())
                .setOrderType(createReq.getType())
                .setPaymentType(createReq.getPaymentType())
                .setUserCouponUuid(StringUtils.isEmpty(createReq.getUserCouponUuid()) ? cart.getUserCouponUuid() : createReq.getUserCouponUuid())
                .setUserCouponNo(cart.getUserCouponNo())
                .setUserPromoLogUuid(cart.getUserPromoLogUuid())
                .setShippingAddressUuid(createReq.getShippingAddressUuid())
                .setPromoCode(cart.getPromoCode())
                .setBuyShippingInsurance(createReq.isBuyShippingInsurance())
                .setShippingAddressUuid(createReq.getShippingAddressUuid())
				.setAmtCash(createReq.getAmtCash()) //Cash现金抵扣金额
                .setPlatform(createReq.getPlatform())
                .setCheckOrder(createReq.isCheckOrder())
                .setOrderChannelUuid(orderChannelUuid);

        req.setItems(new ArrayList<>(createReq.getItems().size()));
        for (CartItemReq cartItem : createReq.getItems()) {
            req.getItems().add(new OrderItemCreateRequest(cartItem.getSkuUuid(), cartItem.getQuantity()));
        }
        orderCreatePrepareHandler.handler(req);

		OrderDTO order = orderMapper.toDto(req.getUuid());
		if (createReq.isCheckOrder()) {
		    return order;
        }
		context.publishEvent(new OrderCreatedEvent(order));

//        orderLogActionUtil.logAction(order,EActionType.ORDER_CREATE);
		return order;
    }

    //    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public OrderDTO createOrder(String userUuid, OrderCreateReq createReq) {
//        UserEntity userEntity = userService.findByUserUuid(userUuid);
//        if(userEntity == null) {
//            throw BusinessException.getInstance(ResultEnum.NOT_FOUND);
//        }
//
//        // 检查快递地址
//        ShippingAddressEntity shippingAddress = this.shippingAddressRepository.getByUuid(createReq.getShippingAddressUuid());
//        if(shippingAddress == null) {
//            throw BusinessException.getInstance(ResultEnum.NOT_FOUND);
//        }
//
//        OrderEntity order = newOrderEntity(userEntity, shippingAddress, createReq);
//
//        // 创建item
//        List<OrderItemEntity> orderItems = _createOrderItems(createReq);
//
//        // 设置原始金额
//        BigDecimal originalAmtSku = orderItems.stream().map(OrderItemEntity::getAmtSku).reduce(BigDecimal.ZERO, BigDecimal::add);
//        BigDecimal originalAmtShipping = orderItems.stream().map(OrderItemEntity::getAmtShipping).reduce(BigDecimal.ZERO, BigDecimal::add);
//        order.setOriginalAmtProduct(originalAmtSku);
//        order.setOriginalAmtShipping(originalAmtShipping);
//        order.setAmt(MoneyUtil.add(originalAmtSku, originalAmtShipping));
//        order.setOriginalAmt(MoneyUtil.add(originalAmtSku, originalAmtShipping));
//
//        // 计算item金额
//        this.computeItemAmt(createReq, orderItems, originalAmtShipping);
//
//        // 真实价格
//        BigDecimal realAmtSku = orderItems.stream().map(OrderItemEntity::getAmtSku).reduce(BigDecimal.ZERO, BigDecimal::add);
//        order.setAmtProductCoupon(orderItems.stream().filter(o -> o.getAmtSkuCoupon() != null).map(OrderItemEntity::getAmtSkuCoupon).reduce(BigDecimal.ZERO, BigDecimal::add));
//
//        // 实际金额
//        order.setAmtProduct(realAmtSku);
//        order.setAmtShipping(orderItems.stream().map(OrderItemEntity::getAmtShipping).reduce(BigDecimal.ZERO, BigDecimal::add));
//
//        order.setAmtSaleTax(saleTaxStrategy.strategy(realAmtSku));
//
//        if (createReq.isBuyShippingInsurance()) {
//            order.setAmtShippingInsurance(shippingInsuranceStrategy.strategy());
//        }
//
//        order.setAmt(MoneyUtil.add(order.getAmtProduct(), order.getAmtShipping(), order.getAmtSaleTax(), order.getAmtShippingInsurance()));
//
//        // 订单商品数量信息
//        order.setSum(orderItems.stream().mapToInt(OrderItemEntity::getQuantity).sum());
//
//        // 订单货币使用第一个商品的货币
//        order.setCurrency(orderItems.get(0).getProduct().getCurrency());
//
//        // ============数据库操作
//
//        //设置默认地址
//        setDefaultShippingAddress(shippingAddress, userUuid);
//
//        // 设置订单流转记录
//        setCreateFlow(order);
//
//        orderItems.forEach(item -> item.setOrder(order));
//        order.setItems(orderItems);
//
//        OrderItemEntity orderItemEntity = orderItems.get(0);
//        order.setStoreUuid(orderItemEntity.getProduct().getStoreUuid());
//        order.setRetailerUuid(orderItemEntity.getProduct().getRetailerUuid());
//
//        order.setNo(generateNo(order));
//
//        //订单信息
//        orderRepository.save(order);
//
//        //快照
//        orderSnap(order, orderItems);
//
//        return new OrderDTO(order);
//    }
//
//    private void computeItemAmt(OrderCreateReq orderCreateReq, List<OrderItemEntity> orderItems, BigDecimal originalAmtShipping) {
//
//        // 折扣率
//        List<UseCouponBo> useCoupons = getUseCouponRate(orderCreateReq.getUserCouponUuid());
//
//        if(!CollectionUtils.isEmpty(useCoupons)){
//            // 计算商品价格
//            orderItems.forEach(orderItem -> {
//
//                BigDecimal price = MoneyUtil.setScale(OrderUseCouponStrategy.strategy(orderItem.getPrice(), useCoupons));
//                orderItem.setPrice(price);
//
//                BigDecimal amtSku = MoneyUtil.mul(price, BigDecimal.valueOf(orderItem.getQuantity()));
//
//                // 优惠价格
//                orderItem.setAmtSkuCoupon(MoneyUtil.sub(orderItem.getAmtSku(), amtSku));
//
//                // 实际金额
//                orderItem.setAmtSku(amtSku);
//
//                // 单商品总价
//                orderItem.setAmt(MoneyUtil.add(orderItem.getAmtSku(), orderItem.getAmtShipping()));
//            });
//        }
//
//        BigDecimal amtSku = orderItems.stream().map(OrderItemEntity::getAmtSku).reduce(BigDecimal.ZERO, BigDecimal::add);
//
//        // 是否去除运费
//        BigDecimal shippingMoney = shippingStrategy.strategy(amtSku, originalAmtShipping, BigDecimal.valueOf(Long.valueOf(sysParamService.getValue(ISysParamService.SYS_PARAM_ORDER_SHIPPING))));
//
//        if (MoneyUtil.equals(shippingMoney, originalAmtShipping)) {
//            return;
//        }
//
//        orderItems.forEach(orderItem -> {
//            // 运费
//            orderItem.setAmtShipping(MoneyUtil.isNullOrZero(shippingMoney) ? BigDecimal.ZERO : orderItem.getAmtShipping());
//
//            // 单商品总价
//            orderItem.setAmt(MoneyUtil.add(orderItem.getAmtSku(), orderItem.getAmtShipping()));
//        });
//    }
//
//    /**
//     * flows
//     * @param orderEntity
//     */
//    private void setCreateFlow(OrderEntity orderEntity) {
//        OrderFlowEntity orderFlowEntity = this.orderFlowService.flowOrder(orderEntity);
//        orderEntity.setFlows(new ArrayList<>());
//        orderEntity.getFlows().add(orderFlowEntity);
//    }
//
//    /**
//     * 设置默认地址
//     * @param shippingAddress
//     * @param userUuid
//     */
//    private void setDefaultShippingAddress(ShippingAddressEntity shippingAddress, String userUuid) {
//        // 把最后一次使用的收货地址改为默认地址
//        if(shippingAddress.getIsDefault() == 0) {
//            // 首先把原来的默认地址改为非默认
//            this.shippingAddressRepository.changeDefault2NoN(userUuid);
//            shippingAddress.setIsDefault(1);
//            this.shippingAddressRepository.save(shippingAddress);
//        }
//    }
//
//    /**
//     *
//     * @param userEntity
//     * @param shippingAddress
//     * @param createReq
//     * @return
//     */
//    private OrderEntity newOrderEntity(UserEntity userEntity, ShippingAddressEntity shippingAddress, OrderCreateReq createReq) {
//
//        OrderEntity order = new OrderEntity();
//        order.setPayed(false);
//        order.setSynced(false);
//        order.setState(EOrderState.START);
//        /*
//         * 订单用户信息
//         */
//        order.setUserUuid(userEntity.getUuid());
//        order.setUser(userEntity);
//
//        // 订单购买类型信息，0表示单独买，1表示拼团买
//        order.setType(createReq.getType());
//
//        // =============订单支付信息============
//        // 支付方式
//        order.setPaymentExpiredAt(DateUtil.addSeconds(DateUtil.now(), scheduleTimeProperties.getOrderUnPaidAutoCancelSecond()));
//
//        // 状态
//        order.signal();
//
//        // 地址信息
//        order.setShippingAddressUuid(createReq.getShippingAddressUuid());
//        order.setShippingAddressFirstName(shippingAddress.getFirstName());
//        order.setShippingAddressLastName(shippingAddress.getLastName());
//        order.setShippingAddressItu(shippingAddress.getItu());
//        order.setShippingAddressPhone(shippingAddress.getPhone());
//        order.setShippingAddressCountry(shippingAddress.getCountry());
//        order.setShippingAddressProvince(shippingAddress.getProvince());
//        order.setShippingAddressCity(shippingAddress.getCity());
//        order.setShippingAddressZipCode(shippingAddress.getZipCode());
//        order.setShippingAddressLine1(shippingAddress.getAddressLine1());
//        order.setShippingAddressLine2(shippingAddress.getAddressLine2());
//
//        //优惠券
//        if(!StringUtils.isBlank(createReq.getUserCouponUuid())){
//            order.setUserCouponUuid(createReq.getUserCouponUuid());
//        }
//
//        // ===============额外初始化信息=============
//        // 每个订单子项只可以退一次
//        order.setRefundMax(createReq.getItems().size());
//
//        return order;
//    }
//
//    private void orderSnap(OrderEntity order, List<OrderItemEntity> items) {
//        orderSnapService.saveOrderSkuSnap(order,items);
//    }
//
//    private List<OrderItemEntity> _createOrderItems(OrderCreateReq createReq) {
//        List<OrderItemEntity> items = new ArrayList<>();
//        for(CartItemReq item : createReq.getItems()) {
//            items.add(_createOrderItem(item));
//        }
//        return items;
//    }
//
//    private OrderItemEntity _createOrderItem(CartItemReq item) {
//        SkuEntity sku = getProductSku(item.getSkuUuid());
//        ProductEntity product = getProduct(sku.getProductUuid());
//
//        OrderItemEntity orderItem = new OrderItemEntity();
//
//        // 订单Product信息
//        orderItem.setProductUuid(sku.getProductUuid());
//        orderItem.setProduct(product);
//
//        // 订单SKU信息
//        orderItem.setSkuUuid(item.getSkuUuid());
//        orderItem.setSku(sku);
//        orderItem.setQuantity(item.getQuantity());
//        orderItem.setPrice(sku.getRetailPrice());
//
//        // 设置原始金额
//        orderItem.setAmtSku(orderItem.amtSku());
//        orderItem.setOriginalAmtSku(orderItem.getAmtSku());
//
//        orderItem.setAmtShipping(orderItem.amtShipping());
//        orderItem.setOriginalAmtShipping(orderItem.getAmtShipping());
//
//        orderItem.setAmt(orderItem.amt());
//        orderItem.setOriginalAmt(orderItem.getAmt());
//
//        //
//        reduceSkuStock(orderItem.getQuantity(), sku);
//
//        return orderItem;
//    }
//
//    // 减库存
//    private void reduceSkuStock(Integer quantity, SkuEntity sku) {
//        sku.setQuantity(sku.getQuantity() - quantity);
//        this.skuRepository.save(sku);
//    }
//
//    private ProductEntity getProduct(String productUuid) {
//        // 检查商品信息
//        ProductEntity product = this.productRepository.getByUuid(productUuid);
//        if(product == null) {
//            throw BusinessException.getInstance(ResultEnum.NOT_FOUND);
//        }
//
//        // 检查商品是否已下架，或者处于其他状态，只有在0的状态才能下单
//        if(product.getStatus() != 0) {
//            throw BusinessException.getInstance(ResultEnum.ORDER_PRODUCT_OFF_SHELVES);
//        }
//
//        return product;
//    }
//
//    private SkuEntity getProductSku(String productSkuUuid) {
//        // 必须传递SKUID
//        if (StringUtils.isBlank(productSkuUuid)) {
//            throw BusinessException.getInstance(ResultEnum.ORDER_ITEM_MUST_INCLUDE_SKU);
//        }
//        // 检查商品SKU信息
//        SkuEntity sku = this.skuRepository.getByUuid(productSkuUuid);
//        if(sku == null) {
//            throw BusinessException.getInstance(ResultEnum.NOT_FOUND);
//        }
//        return sku;
//    }
//
//    private List<UserCouponBo> getUseCouponRate(String userCouponUuid) {
//        if (StringUtils.isBlank(userCouponUuid)) {
//            return new ArrayList<>(0);
//        }
//
//        UserCouponEntity canUseCoupon = userCouponService.getCanUseCoupon(userCouponUuid);
//
//        UserCouponBo useCouponBo = new UserCouponBo(canUseCoupon);
//
//        List<UserCouponBo> userCoupons = new ArrayList<>();
//        if (userCoupons != null) {
//            userCoupons.add(useCouponBo);
//        }
//        return userCoupons;
//    }


//
//    private String generateNo(OrderEntity order){
//        String merchat = order.getRetailerUuid() + "", store = order.getStoreUuid() + "", user = order.getUserUuid() + "";
//
//        Long random = sysSequenceService.getNext(ISysSequenceService.ORDER_NO + merchat + store + user);
//
//        String no = OrderNoUtil.generate(serverNodeNo, merchat, store, user, random);
//
//        log.info(">>>>>>>> generate order no >>>>>>>>> nodeNo:{},merchatNo:{},storeNo:{},userNo:{},random:{} >>>>> orderNo:{}", serverNodeNo, merchat, store, user, random, no);
//
//        return no;
//    }
}

